package com.hmdp.core.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.hmdp.common.constant.RedisConstants;
import com.hmdp.core.service.IUserService;
import com.hmdp.entity.db.Follow;
import com.hmdp.core.mapper.FollowMapper;
import com.hmdp.core.service.IFollowService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.entity.db.User;
import com.hmdp.entity.dto.Result;
import com.hmdp.entity.dto.UserDTO;
import com.hmdp.utils.UserHolder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Slf4j
@Service
public class FollowServiceImpl extends ServiceImpl<FollowMapper, Follow> implements IFollowService {

    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Resource
    private IUserService userService;

    @PostConstruct
    public void initFollow() {
        log.info("初始化共同关注缓存start");
        List<Follow> follows = this.list(new LambdaQueryWrapper<>(null));
        Map<Long, List<Follow>> map = follows.stream().collect(Collectors.groupingBy(Follow::getUserId));
        map.forEach((k,v) -> {
            String key = RedisConstants.FOLLOW_KEY + k;
            stringRedisTemplate.delete(key);
            stringRedisTemplate.opsForSet().add(key, v.stream().map(m-> m.getFollowUserId().toString()).toArray(String[]::new));
        });
        log.info("初始化共同关注缓存end");
    }

    @Override
    public Result follow(Long followUserId, Boolean isFollow) {
        Long userId = UserHolder.getUser().getId();
        String key = RedisConstants.FOLLOW_KEY + userId;
        if(isFollow) {
            Follow follow = new Follow();
            follow.setUserId(userId);
            follow.setFollowUserId(followUserId);
            boolean isSuccess = save(follow);
            if(isSuccess) {
                //把关注用户的id，放入redis的set集合
                stringRedisTemplate.opsForSet().add(key,followUserId.toString());
            }
        } else {
            boolean isSuccess = this.lambdaUpdate()
                    .eq(Follow::getFollowUserId,followUserId)
                    .eq(Follow::getUserId,userId)
                    .remove();
            if(isSuccess) {
                stringRedisTemplate.opsForSet().remove(key,followUserId.toString());
            }
        }
        return Result.ok();
    }

    @Override
    public Result isFollow(Long followUserId) {
        Long userId = UserHolder.getUser().getId();
        boolean exists = this.lambdaQuery()
                .eq(Follow::getFollowUserId, followUserId)
                .eq(Follow::getUserId, userId)
                .exists();
        return Result.ok(exists);
    }

    @Override
    public Result followCommon(Long id) {
        Long userId = UserHolder.getUser().getId();
        String key = RedisConstants.FOLLOW_KEY + userId;
        String key2 = RedisConstants.FOLLOW_KEY + id;
        Set<String> intersect = stringRedisTemplate.opsForSet().intersect(key, key2);
        if(intersect == null || intersect.isEmpty()) {
            return Result.ok(Collections.emptyList());
        }
        List<Long> ids = intersect.stream().map(Long::valueOf).collect(Collectors.toList());
        List<UserDTO> userDTOS = userService.listByIds(ids).stream()
                .map(user -> BeanUtil.copyProperties(user, UserDTO.class))
                .collect(Collectors.toList());
        return Result.ok(userDTOS);
    }
}
